package com.crcode.crm.controller.data;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crcode.crm.bean.data.ProjectBean;
import com.crcode.crm.bean.log.DataLogBean;
import com.crcode.crm.bean.user.UserBean;
import com.crcode.crm.service.data.ProjectService;
import com.crcode.crm.service.log.DataLogService;
import com.crcode.crm.service.retrieval.RetrievalService;
import com.crcode.crm.utils.DateUtil;
import com.crcode.crm.utils.MyFileUtil;
import com.crcode.crm.utils.PageVo;
import com.crcode.crm.utils.ResultPageUtil;
import com.crcode.crm.utils.ResultUtil;


/**
 * 项目控制层
 * @author cl
 * @date 2019年3月26日
 */
@Controller
public class ProjectController {
	
	@Resource(name = "projectService")
	private ProjectService projectService;
	
	@Autowired
	private RetrievalService retrievalService;
	
	@Resource(name = "logService")
	private DataLogService logService;
	
	/**
	 * 项目保存
	 * @param request request
	 * @param session session
	 * @param project project对象
	 * @return
	 */
	@RequestMapping(value="/project/save",method=RequestMethod.POST)
	@ResponseBody
	public ResultUtil save(HttpServletRequest request,HttpSession session,ProjectBean project){
		ResultUtil ru = new ResultUtil();
		Object obj = session.getAttribute("user");
		if(obj==null){
			ru.setStatus(false);
            ru.setInfo("未登录，请先登录");
            return ru;
		}
		
		UserBean user = JSONObject.parseObject(obj.toString(), UserBean.class);
		String nowTime=DateUtil.DateToStr(new Date(), "yyyy-MM-dd HH:mm:ss");
		
		 // 保存之前的对象JSON，后面存日志
		String beforeSaveBean = null;
		String remarks = null; 
		
		if(project.getId()==null){//新增
			ProjectBean p=projectService.findByProNameAndEntUuid(project.getProName(),project.getEntUuid());
			if(p!=null){
				 ru.setStatus(false);
                 ru.setInfo("项目名称已存在");
                 return ru;
			}
			project.setCreateTime(nowTime);
			project.setCreateUserUuid(user.getUuid());
			project.setCreateUserName(user.getUserRealName());
			//新增责任人赋值为创建者
			project.setLiableUserUuid(user.getUuid());
			project.setLiableUserName(user.getUserRealName());
			remarks = "项目资源新增";
		}else{
			beforeSaveBean = JSON.toJSONString(projectService.getById(project.getId()));
			remarks = "项目资源编辑";
		}
		Boolean is=projectService.saveResultBoolean(project);
		ru.setInfo(is ? "操作成功！" : "操作失败!");
		ru.setStatus(is);
		ru.setObj(project);
		
		//保存日志
		DataLogBean l = new DataLogBean();
		l.setUserUuid(user.getUuid());
		l.setUserName(user.getUserRealName());
		l.setOperateTime(nowTime);
		l.setDataTuid(project.getUuid());
		l.setDataTitle(project.getProName());
		l.setLatestContent(JSONObject.toJSONString(project));
		l.setLogType(1);
		l.setOriginalContent(beforeSaveBean);
		l.setOperateRemarks(remarks);
		l.setDetailedType(3);
		logService.saveResultBoolean(l);
		
		return ru;
	}
	
	/**
	 * 根据id查询项目
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/project/findById",method=RequestMethod.POST)
	@ResponseBody
	public ProjectBean findById(HttpServletRequest request,Integer id){
		return projectService.getById(id);
	}
	/**
	 * 根据uuid查询项目
	 * @param request
	 * @param uuid
	 * @return
	 */
	@RequestMapping(value="/project/findByUuid",method=RequestMethod.POST)
	@ResponseBody
	public ProjectBean findByUuid(HttpServletRequest request,String uuid){
		return projectService.findByUuid(uuid);
	}
	/**
	 * 根据主键批量物理删除
	 * @param request
	 * @param session
	 * @param ids
	 * @return
	 */
	@RequestMapping(value="/project/physicalDeleteByIds",method=RequestMethod.POST)
	@ResponseBody
	public ResultUtil physicalDeleteByIds(HttpServletRequest request,HttpSession session,String ids){
		ResultUtil r=new ResultUtil();
		Object obj = session.getAttribute("user");
		UserBean user = JSONObject.parseObject(obj.toString(), UserBean.class);
		if(user==null){
			r.setStatus(false);
			r.setInfo("用户未登录，请先登录！");
			r.setObj(null);
			return r;
		}
		return projectService.physicalDeleteByIds(ids,user);
	}

	/**
	 * 分页条件查询
	 * @param request request
	 * @param session session
	 * @param conditions 查询条件
	 * @param vo page
	 * @return Map<String, Object>
	 */
	@RequestMapping(value = "/project/findBySpec", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> findByEntUuid(HttpServletRequest request, HttpSession session, String conditions, PageVo vo) {
		Map<String,Object> params=JSONObject.parseObject(conditions);
		return projectService.findAll(params,vo);
	}
	/**
     * 批量单一授权
     * @author lxw
     * @date 2019年4月9日
     * @param request
     * @param session
     * @param uuids 资源UUIDS
	 * @param suuid 查看权限用户UUIDS
	 * @param sname查看权限用户名称集
	 * @param euuid编辑 权限用户UUIDS
	 * @param ename编辑权限用户名称集
	 * @param user 当前操作用户
     * @return
     */
    @RequestMapping(value="/project/projectEmpowerByUuids", method = RequestMethod.POST)
    @ResponseBody
    public ResultUtil empowerByUuids(HttpServletRequest request, HttpSession session, String uuids,String suuid,String sname,String euuid,String ename){
        ResultUtil r=new ResultUtil();
		Object obj = session.getAttribute("user");
		UserBean user = JSONObject.parseObject(obj.toString(), UserBean.class);
		if(user==null){
			r.setStatus(false);
			r.setInfo("用户未登录，请先登录！");
			r.setObj(null);
			return r;
		}
        boolean is = this.projectService.empowerByIds(uuids, suuid, sname, euuid, ename, user);
       r.setInfo(is?"操作成功":"操作失败");
       r.setStatus(is);
       return r;
    }
    /**
     * 用户查看项目提醒消息之后更改项目提醒的状态
     * @author lxw
     * @date 2019年4月18日
     * @param request
     * @param session
     * @param uuid
     * @return
     */
    @RequestMapping(value="/project/userReadMessageChangeReadStats", method = RequestMethod.POST)
    @ResponseBody
    public ResultUtil userReadMessageChangeReadStats(HttpServletRequest request,HttpSession session,String uuid){
    	ResultUtil r=new ResultUtil();
    	ProjectBean pro = this.projectService.findByUuid(uuid);
    	pro.setReadStats(1);
    	boolean is = this.projectService.saveResultBoolean(pro);
    	r.setInfo(is?"操作成功":"操作失败");
        r.setStatus(is);
    	return r;
    }
    
    /**
	 * 设置项目的启动或者终止
	 * @author lxw
	 * @date 2019年4月19日
	 * @param isEnd 0、正常，1、终止
	 * @param uuids
	 * @return
	 */
    @RequestMapping(value="/project/setProjectStartOrEnd", method = RequestMethod.POST)
    @ResponseBody
	public ResultUtil setProjectStartOrEnd(HttpServletRequest request,HttpSession session,Integer isEnd, String uuids){
    	Object obj = session.getAttribute("user");
		UserBean user = JSONObject.parseObject(obj.toString(), UserBean.class);
		return this.projectService.setProjectStartOrEnd(user,isEnd,uuids);
	}
    
    /**
     * 重置负责人
     * @author lxw
     * @date 2019年4月26日
     * @param request
     * @param session
     * @param userUuid
     * @param userName
     * @param uuids
     * @return
     */
    @RequestMapping(value="/project/resetLiableUserByUuids", method = RequestMethod.POST)
    @ResponseBody
	public ResultUtil resetLiableUserByUuids(HttpServletRequest request,HttpSession session, String userUuid, String userName, String uuids){
    	Object obj = session.getAttribute("user");
		UserBean user = JSONObject.parseObject(obj.toString(), UserBean.class);
		return this.projectService.resetLiableUserByUuids(user, uuids, userUuid, userName);
	}
    
    /**
	 * 导出表格
	 * @param request
	 * @param response
	 * @param session
	 * @throws Exception
	 */
    @ResponseBody
    @RequestMapping(value="/project/exportExcel", method = RequestMethod.POST)
	public void resetLiableUserByUuids(HttpServletRequest request,HttpServletResponse response,HttpSession session) throws Exception{
    	Object obj = session.getAttribute("user");
		UserBean user = JSONObject.parseObject(obj.toString(), UserBean.class);
		String datas=request.getParameter("datas");
		JSONObject dataObj=JSONObject.parseObject(datas);
		PageVo vo=new PageVo();
		vo.setPageSize(Integer.parseInt(dataObj.getString("pageSize")));
		vo.setPageIndex(Integer.parseInt(dataObj.getString("pageIndex")));
		vo.setOrderBy(dataObj.getString("orderBy"));
		vo.setOrderDesc(Integer.parseInt(dataObj.getString("orderDesc")));
		ResultPageUtil ru=retrievalService.comSearch(dataObj.getString("table"), dataObj.getString("text"), dataObj.getString("higthText"),vo, user);
		Map<String,Object> map=new HashMap<>();
		map.put("rows", JSON.toJSONString(ru.getRows()));
		map.put("column", dataObj.getString("column"));
		map.put("type","project");
		try {
			MyFileUtil.exp(request, response, JSON.toJSONString(map));
		} catch (IOException e) {
			throw new Exception("导出文件错误",e);
		}
	}
}
